<?php


namespace EchoPHP\Foundation\BootStrap;

use Dotenv\Dotenv;
use Dotenv\Environment\Adapter\EnvConstAdapter;
use Dotenv\Environment\Adapter\PutenvAdapter;
use Dotenv\Environment\Adapter\ServerConstAdapter;
use Dotenv\Environment\DotenvFactory;
use Dotenv\Exception\InvalidFileException;
use EchoPHP\Foundation\Application;

/**
 * 加载应用程序定义的环境变量，该环境变量只在当前应用程序生效
 * @package EchoPHP\Foundation\BootStrap
 */
class LoadAppEnvironment {

    /**
     * 加载项目环境变量
     * @param Application $app
     */
    public function bootstrap(Application $app) {
        try {
            $this->createDotEnv($app)->safeLoad();
        } catch (InvalidFileException $e) {
            //项目环境变量解析出错，因为此时尚未注册异常处理，所以直接终止程序
            $errorMsg = 'The environment file is invalid!' . $e->getMessage();
            error_log($errorMsg, 0);
            exit('系统繁忙，请稍后再试');
        }
    }

    /**
     * 构建ditenv实例
     * @param Application $app
     * @return Dotenv
     */
    protected function createDotEnv(Application $app) {
        return Dotenv::create(
            $app->environmentPath(),
            $app->environmentFile(),
            new DotenvFactory([new PutenvAdapter()])
        );
    }
}